import redis


class RedisClient(object):

    """ Работа с Redis определена в этом классе """

    def __init__(self, db=0):

        self.host = 'localhost'
        self.port = 6379
        self.db = db
        self.redis_client = redis.StrictRedis(host=self.host, port=self.port, db=self.db)


    def increase_number_views(self, request, product):

        """ Увеличиваем количество просмотров продукта """

        if not request.user.is_authenticated:
            viewed_users = self.redis_client.get('product:{}:view'.format(product.id))
            if viewed_users: return int(viewed_users)
            else: return 0

        viewed_users = map(int, self.redis_client.lrange('product:{}:view:persons'.format(product.id),
                                                         start=0, end=-1))

        if viewed_users is None or request.user.id not in viewed_users:
            number_views = self.redis_client.incr('product:{}:view'.format(product.id))
            viewed_users = self.redis_client.rpush('product:{}:view:persons'.format(product.id),
                                                   request.user.id)
            return number_views

        else:
            viewed_users = self.redis_client.get('product:{}:view'.format(product.id))
            return int(viewed_users)
